package com.generalaj.console.configuration.workflow;

import java.util.HashSet;
import java.util.Set;

/**
 * Created by wangxin on 2017/2/27.
 */
public class GraphManager {

    private Set<GraphNode> allNodes =new HashSet<GraphNode>();

    public GraphNode createRootNode(){
        GraphNode root=new GraphNode("root","root");
        allNodes.add(root);
        return root;
    }

    public GraphNode addNext(GraphNode current,String type,String name){
        GraphNode result=null;
        if(allNodes.contains(new GraphNode(type,name,current.getRoot()))){
            for(GraphNode node: allNodes){
                if(node.getType().equals(type) && node.getName().equals(name)){
                    result=node;
                    break;
                }
            }
        }else{
            result=new GraphNode(type,name,current.getRoot());
            allNodes.add(result);
        }
        current.addNext(result);
        return result;
    }

    public Set<GraphNode> getAllNodes() {
        return allNodes;
    }
    public Set<GraphNode> getDependencies(GraphNode node){
        Set<GraphNode> nodes=getAllNodes();
        Set<GraphNode> results=new HashSet<GraphNode>();
        for(GraphNode current:nodes){
            if(current.getNext().contains(node)){
                results.add(current);
            }
        }
        return results;
    }

    public static void main(String[] args){
        GraphManager maker=new GraphManager();
        GraphNode root=maker.createRootNode();
        GraphNode a=maker.addNext(root,"init","init_workspace");
        GraphNode b=maker.addNext(root,"init","init_workspace");
        GraphNode c=maker.addNext(b,"ccc","ccc");
        GraphNode d=maker.addNext(root,"ddd","ddd");
        maker.addNext(d,"ccc","ccc");
        System.out.println(maker.getAllNodes().size());
        System.out.println(maker.getDependencies(c).size());
    }

}
